package org.jeecg.modules.app.order.controller;

import cn.felord.payment.wechat.v3.WechatApiProvider;
import cn.felord.payment.wechat.v3.model.Amount;
import cn.felord.payment.wechat.v3.model.PayParams;
import cn.felord.payment.wechat.v3.model.Payer;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.ApiLogin;
import org.jeecg.common.util.IPUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.app.order.service.AliPayService;
import org.jeecg.modules.app.user.vo.ResultUser;
import org.jeecg.modules.app.util.NumberArithmeticUtils;
import org.jeecg.modules.power.device.entity.YlDevice;
import org.jeecg.modules.power.device.service.IYlDeviceService;
import org.jeecg.modules.power.group.entity.GroupUser;
import org.jeecg.modules.power.group.service.IYlGroupService;
import org.jeecg.modules.power.order.entity.YlMemberOrder;
import org.jeecg.modules.power.order.service.IYlMemberOrderService;
import org.jeecg.modules.power.shop.entity.YlShop;
import org.jeecg.modules.power.shop.service.IYlShopService;
import org.jeecg.modules.power.user.entity.YlMember;
import org.jeecg.modules.power.user.entity.YlUser;
import org.jeecg.modules.power.user.service.IYlMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: jeecg-boot-parent
 * @BelongsPackage: org.jeecg.modules.app.order.controller
 * @Author: mi
 * @CreateTime: 2024-07-13 11:17
 * @Description:
 */
@CrossOrigin
@Api(tags = "小程序会员订单相关")
@RestController
@RequestMapping("/api/programOrder")
public class ProgramOrderController {


    @Autowired
    private AliPayService aliPayService;//支付宝 下单工具类

    @Autowired
    private IYlMemberService ylMemberService;

    @Autowired
    private IYlMemberOrderService ylMemberOrderService;//会员订单表


    @Autowired
    private IYlShopService ylShopService;//店铺表

    @Autowired
    private IYlDeviceService ylDeviceService;//设备表

    //小组
    @Autowired
    private IYlGroupService ylGroupService;


//    String TENANT_ID = "mobile";
//
//    @Autowired
//    private WechatApiProvider wechatApiProvider;//





    //获取会员卡数据

    @ApiLogin
    @ApiOperation("小程序获取会员卡数据")
    @GetMapping("/getMemberList")
    public Result<List<YlMember>> getMemberList(){
      Result<List<YlMember>> result = new Result<List<YlMember>>();
      List<YlMember>memberList= ylMemberService.list(new QueryWrapper<YlMember>().lambda().orderByAsc(YlMember::getType));
      result.setCode(200);
      result.setResult(memberList);
      return result;
    }

    //小程序 会员下单
    @ApiLogin
    @ApiOperation(value="小程序授权会员卡充值下单", notes="小程序授权会员卡充值下单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "会员卡id", required = true),
            @ApiImplicitParam(name = "payMethod", value = "支付方式1、微信支付 2、支付宝支付 ", required = true),

            @ApiImplicitParam(name = "deviceMac", value = "设备MAC ", required = true),
    })
    @PostMapping(value = "/addPayMemberOrder")
    public Result<?>addPayMemberOrder(HttpServletRequest request,String id,Integer payMethod,String deviceMac)throws AlipayApiException {
//        String createIp = IPUtils.getIpAddr(request);//ip
        YlUser user=new ObjectMapper().convertValue(request.getAttribute("user"),YlUser.class);//转对象 用户登陆对象
        if (user.getIsMember()==1)return Result.error_599("下单失败,现在是会员");
        if (oConvertUtils.isEmpty(id))return Result.error_599("会员卡id不可为空");
        if (oConvertUtils.isEmpty(payMethod))return Result.error_599("支付方式不能为空");
        if(payMethod==1 || payMethod==2){
            YlMember ylMember= ylMemberService.getById(id);
            //生成支付订单号
            String orderNumber = "CZ"+   NumberArithmeticUtils.getCode();
            YlMemberOrder ylMemberOrder=new YlMemberOrder();
            ylMemberOrder.setUserId(user.getId());
            ylMemberOrder.setTel(user.getTel());//手机号
            ylMemberOrder.setPayNumber(orderNumber);
            ylMemberOrder.setPayMethod(payMethod);
            ylMemberOrder.setMemberId(ylMember.getId());
            ylMemberOrder.setName(ylMember.getName());
            ylMemberOrder.setPayPrice(ylMember.getPrice());
            ylMemberOrder.setPayStatus(0);
            ylMemberOrder.setType(ylMember.getType());
            ylMemberOrder.setMonth(ylMember.getMonth());
            ylMemberOrder.setFreeDuration(ylMember.getFreeDuration());

            if (oConvertUtils.isEmpty(deviceMac)){//扫码设备进入的 购买会员


               List<YlDevice>ylDeviceList= ylDeviceService.list(new QueryWrapper<YlDevice>().eq("device_mac",deviceMac));
                if (ylDeviceList.size()>0){
                    ylMemberOrder.setDeviceMac(deviceMac);

                    YlShop ylShop=ylShopService.getById(ylDeviceList.get(0).getBusinessId());
                    if (oConvertUtils.isNotEmpty(ylShop)){
                        ylMemberOrder.setShopId(ylShop.getId());
                        ylMemberOrder.setShopName(ylShop.getShopName());
                        ylMemberOrder.setBdId(ylShop.getBdId());
                        ylMemberOrder.setBdName(ylShop.getShopBd());
                        //根据业务员id  获取 组织信息
                        GroupUser groupUser = ylGroupService.getUserGroup(ylShop.getBdId());
                        if (oConvertUtils.isNotEmpty(groupUser)){
                            ylMemberOrder.setGroupId(groupUser.getGroupId());//组织id
                            ylMemberOrder.setGroupName(groupUser.getGroupName());//组织名称
                        }
                    }
                }
                //等设计出来 再说
//                ylMemberOrder.setShopId("");
            }
            ylMemberOrderService.save(ylMemberOrder);
            if (payMethod==1){
//                String price = ylMemberOrder.getPayPrice().multiply(new BigDecimal(100)).toString().split("\\.")[0];
//                //微信小程序支付
//                PayParams payParams = new PayParams();
//
//                payParams.setDescription("会员充值");
//                //
//                // 商户侧唯一订单号 建议为商户侧支付订单号 订单表主键 或者唯一标识字段
//                payParams.setOutTradeNo(orderNumber);
//                // 需要定义回调通知
//                payParams.setNotifyUrl("/wxpay/callbacks/transaction");
//                Amount amount = new Amount();
//                amount.setTotal(Integer.parseInt(price));//钱 分
//                payParams.setAmount(amount);
//                // 此类支付  Payer 必传  且openid需要同appid有绑定关系 具体去看文档
//                Payer payer = new Payer();
//                payer.setOpenid(user.getOpenid());
//                payParams.setPayer(payer);
//                 wechatApiProvider.directPayApi(TENANT_ID)
//                        .jsPay(payParams)
//                        .getBody();
                return Result.error_599("未开发");
            }else {
                //支付宝小程序支付
                return aliPayService.returnAliPayData(orderNumber, ylMemberOrder.getPayPrice().toString(), "会员充值", user);
            }
        }
        return Result.error_599("支付方式错误");
    }









}
